package
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.getTimer;
	
	[SWF(width=480, height=320, frameRate=24, backgroundColor=0xE2E2E2)]
	public class ActionScriptBlittingPart3 extends Sprite
	{
		
		public function ActionScriptBlittingPart3()
		{
			init();
			stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
			stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
		}
		
		[Embed(source="spritesheets/browncollector.png")]
		public var BrownCollector:Class;
		
		public var canvas:BitmapData;
		public var canvasClearRect:Rectangle;
		public var spritesheet:BitmapData;
		public var rect:Rectangle;
		private var currentTile:int = 0;
		
		private var collectorX:int = 20;
		private var collectorY:int = 30;
		private var destX:int = 20;
		private var destY:int = 30;
		
		
		private var tickPosition:int = 0;
		private var tickLastPosition:int = -1;
		private var framePeriod:int = 66;//33; // 1000 / 20 - (1 sec / frame rate)
		
		/**
		 * 	Initialize method
		 */
		private function init():void
		{
			// Set our game timer to the stage frameRate
			framePeriod = int(1000 / stage.frameRate);
			
			// Create input bitmap instance
			spritesheet = (new BrownCollector() as Bitmap).bitmapData;
			
			// Add a Bitmap to the display list that will copyPixels() to.
			canvas = new BitmapData(480, 320, true, 0xFFFFFF);
			addChild(new Bitmap(canvas));
			
			canvasClearRect = new Rectangle(0, 0, 480, 320);
			// Tile Size
			rect = new Rectangle(0, 0, 40, 40);
			
		}
		
		/**
		 * 	Handles the timer
		 */
		private function enterFrameHandler(event:Event):void
		{
			tickPosition = int((getTimer() % 1000) / framePeriod);
			trace(int((getTimer() % 1000)));
			if (tickLastPosition != tickPosition)
			{
				tickLastPosition = tickPosition;
				canvas.lock();
				canvas.fillRect(canvasClearRect, 0x000000);
				render();
				canvas.unlock();
			}
		}
		
		/**
		 * 	Render any bitmap data.
		 */
		private function render():void
		{			
			rect.x = (currentTile % 5) * 40;
			rect.y = int(currentTile / 5) * 40;
			collectorX += (destX-collectorX-20)/5;
			collectorY += (destY - collectorY - 30) / 5;
			
			canvas.copyPixels(spritesheet, rect, 
					new Point(collectorX, collectorY), null, null, true);
			currentTile = ++currentTile % 20;
		}
		
		/**
		 * 	Used to move the animation around.
		 */
		private function mouseUpHandler(event:MouseEvent):void
		{
			destX = event.stageX;
			destY = event.stageY;
		}
	}
}